package com.example.demovote.controller;


import com.example.demovote.entity.User;
import com.example.demovote.service.IUserService;
import com.example.demovote.service.ServiceException;
import com.example.demovote.vo.Result;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 投票系统-用户表-4 前端控制器
 * </p>
 *
 * @author ly
 * @since 2024-03-18
 */
@RestController
@RequestMapping("/demovote/user")
public class UserController {

    @Resource
    IUserService userService;

    @RequestMapping("login")
    public Result login(String uname, String pwd, HttpSession session){
        try {
            User user = userService.login(uname, pwd);
            // 将用户对象保存到会话
            session.setAttribute("loginedUser", user);
            Map<String,Object> data = new HashMap<>();
            data.put("user",user);
            data.put("url", session.getAttribute("ServletPath"));
            session.removeAttribute("ServletPath");
            return new Result(1,"登录成功！",data);
        } catch (ServiceException e) {
            e.printStackTrace();
            return new Result(e.getCode(),e.getMessage(),null);
        }
    }

    @RequestMapping("myinfo")
    public Result myinfo(HttpSession session){
        Object user = session.getAttribute("loginedUser");
        if(user==null){
            return new Result(0,"未登录",null);
        } else {
            return new Result(1,"已登录",user);
        }
    }

    @RequestMapping("logout")
    public ModelAndView logout(HttpSession session, ModelAndView mav){
        // 手动让会话失效
        session.invalidate();
        mav.setViewName("redirect:/index.html");
        return mav;
    }

    @RequestMapping("reg")
    public Result register(@Valid User user, Errors errors, String repwd){
        if(errors.hasErrors()){
            return new Result(0, "数据验证失败", errors.getAllErrors());
        }
        if(user.getPwd().equals(repwd) == false){
            errors.reject("repwd", "密码与确认密码不一致！");
            return new Result(0, "数据验证失败", errors.getAllErrors());
        }
        try {
            userService.register(user);
        } catch (ServiceException e) {
            errors.rejectValue("uname", "uname.error", e.getMessage());
            return new Result(0, "数据验证失败", errors.getAllErrors());
        }
        return new Result(1, "注册成功!", user);
    }


}

